package com.battery.netty;

import com.battery.service.DeviceService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


@Component

public class ServerHandler extends ChannelInboundHandlerAdapter{
	
	private static ServerHandler serverHandler;

	private final DeviceService deviceService;

	public ServerHandler(DeviceService deviceService) {
		this.deviceService = deviceService;
	}


	@PostConstruct
	    public void init(){
		 	serverHandler = this;
	    }
	

	public final static Map<String,ChannelHandlerContext> CHANNEL_HANDLER_CONTEXT_MAP = new HashMap<String, ChannelHandlerContext>() {
	};
	
	 @Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//当连接处于活动状态,把连接放到一个容器进行统一的管理
	}

	 
	 @Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		 System.out.println("Chanel is inactive");
		//当连接断掉会触发
	}
	 
	 @Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//当连接读取完信息之后触发
		ctx.flush();
		
	}
	 
	 @Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		 //当管道数据发生异常的时候触发	
		 cause.printStackTrace();
	     ctx.close();
	        
	}
	 
	 @Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//连接建立之后，信息在传输中的时候触发
		//ACT:updata;DEVNAME:110;PRODUCTGROUP:1;NUMOFDEV:20;DEVTEMP:20.55\r\n
		 HashMap<String,String> hashMap=new HashMap<>();
		System.out.println(msg.toString());
		 for (String i:msg.toString().split(";")) {
		 	hashMap.put(i.split(":")[0],i.split(":")[1]);
		 }
		 String ACT=hashMap.get("ACT");
		 if (ACT.equals("login")){
			deviceService.deviceLogin(hashMap,ctx);
		 }
		 else if (ACT.equals("sync_setting")){
			 deviceService.updateDevice(hashMap);
		 }
		 else if(ACT.equals("sync_battery")){
//		 	deviceService.
		 }
		 else if(ACT.equals("rent_confirm")){
		 	deviceService.updateOrder(hashMap);
		 }
		 else if(ACT.equals("return_back")){
			 deviceService.returnBattery(hashMap);
		 }else if(ACT.equals("popup_confirm")){
			 deviceService.popupConfirm(hashMap);
		 }
		 else if(ACT.equals("sync_battery")){
			 deviceService.popupConfirm(hashMap);
		 }
		//假定获取到信息.可以选择对数据加工，对数据做持久话操作

	}
}
